package com.hd.controller.doc.article;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.UnsupportedEncodingException;
import java.util.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.hd.util.Const;
import com.hd.util.html2pdf.WkhtmlToPDF;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hd.controller.base.BaseController;
import com.hd.entity.doc.article.Article;
import com.hd.entity.doc.article.ArticleType;
import com.hd.service.doc.article.ArticleService;
import com.hd.service.doc.article.ArticleTypeService;
import com.hd.util.FileUtil;
import com.hd.util.StringUtils;
import com.hd.util.TransformCharacter;
import com.hd.util.result.PageInfo;
import com.youbenzi.md2.export.FileFactory;


/**
 * 文章
 */
@RequestMapping("article")
@Controller
public class ArticleController extends BaseController {
    @Autowired
    private ArticleService articleService;
    @Autowired
    private ArticleTypeService articelTypeService;

    /**
     * 主页
     *
     * @return
     */
    @RequestMapping("manager")
    public String manager() {
        return "jsp/doc/article/articleList";
    }


    /**
     * 列表
     *
     * @param page
     * @param rows
     * @param sort
     * @param order
     * @return
     */
    @RequestMapping(value = "/dataGrid", method = RequestMethod.POST)
    @ResponseBody
    public Object dataGrid(Article article, Integer page, Integer rows, String sort, String order) {
        PageInfo pageInfo = new PageInfo(page, rows, sort, order);
        Map<String, Object> condition = new HashMap<String, Object>();
        if (StringUtils.isNotNull(article.getTitle())) {
            condition.put("title", article.getTitle());
        }
        if (StringUtils.isNotNull(article.getType())) {
            condition.put("type", article.getType());
        }
        pageInfo.setCondition(condition);
        articleService.selectDataGrid(pageInfo);
        return pageInfo;
    }

    /**
     * 添加页
     *
     * @return
     */
    @RequestMapping("/addPage")
    public String addPage() {
        return "jsp/doc/article/articleAdd";
    }

    /**
     * 添加
     *
     * @param article
     * @return
     */
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    @ResponseBody
    public Object add(Article article) {
        //判断内容是否为空，不为空则转化
        if (StringUtils.isNotNull(article.getHtmlContent())) {
            String content = TransformCharacter.doUntransition(article.getHtmlContent());
            article.setHtmlContent(content);
        }
        //获取类型
        if (StringUtils.isNotNull(article.getType())) {
            ArticleType articleType = articelTypeService.get(article.getType());
            article.setTypeName(articleType.getName());
        }
        article.setCreateTime(new Date());
        if (StringUtils.isNotNull(article.getType())) {
            ArticleType articleType = articelTypeService.get(article.getType());
            if (articleType != null) {
                article.setTypeName(articleType.getName());
            }
        }
        articleService.save(article);
        return renderSuccess("添加成功！");
    }

    /**
     * 删除
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/delete/{id}", method = RequestMethod.POST)
    @ResponseBody
    public Object delete(@PathVariable("id") String id) {
        articleService.delete(id);
        return renderSuccess("删除成功！");
    }

    /**
     * 编辑页
     *
     * @param model
     * @param id
     * @return
     */
    @RequestMapping("/editPage/{id}")
    public String editPage(Model model, @PathVariable("id") String id) {
        Article article = articleService.get(id);
        model.addAttribute("article", article);
        return "jsp/doc/article/articleEdit";
    }

    /**
     * 查看页
     *
     * @param model
     * @param id
     * @return
     */
    @RequestMapping("/viewPage/{id}")
    public String viewPage(Model model, @PathVariable("id") String id) {
        Article article = articleService.get(id);
        model.addAttribute("article", article);
        return "jsp/doc/article/articleView";
    }

    /**
     * 编辑
     *
     * @param article
     * @return
     */
    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    @ResponseBody
    public Object edit(Article article) {
        //判断内容是否为空，不为空则转化
        if (StringUtils.isNotNull(article.getHtmlContent())) {
            String content = TransformCharacter.doUntransition(article.getHtmlContent());
            article.setHtmlContent(content);
        }
        //获取类型
        if (StringUtils.isNotNull(article.getType())) {
            ArticleType articleType = articelTypeService.get(article.getType());
            article.setTypeName(articleType.getName());
        }
        if (StringUtils.isNotNull(article.getType())) {
            ArticleType articleType = articelTypeService.get(article.getType());
            if (articleType != null) {
                article.setTypeName(articleType.getName());
            }
        }
        Article vo = articleService.get(article.getId());
        article.setCreateTime(vo.getCreateTime());
        article.setLastUpdateTime(new Date());
        articleService.update(article);
        return renderSuccess("编辑成功！");
    }

    /**
     * 导出为PDF
     *
     * @param id
     * @param request
     * @param response
     */
    @RequestMapping("/exportPDF")
    public void exportPDF(String id, HttpServletRequest request, HttpServletResponse response) {
        Article article = articleService.get(id);
        String content = article.getContent();
        content = content.replaceAll("&#39;", "'");
        content = content.replaceAll("&quot;", "\"");
        content = content.replaceAll("&lt;", "<");
        content = content.replaceAll("&gt;", ">");
        System.out.println(content);
        String title = article.getTitle();
        String basePath = request.getServletContext().getRealPath("/static/temp");
        File baseFile = new File(basePath);
        if (!baseFile.exists()) {
            baseFile.mkdirs();
        }
        String path = basePath + File.separator + "temp.md";
        FileUtil.writeFile(path, content);
        String targetPath = basePath + File.separator + title + ".pdf";
        if (StringUtils.isNull(title)) {
            targetPath = basePath + File.separator + "1.pdf";
        }
        try {
            FileFactory.produce(new File(path), targetPath);
            String fileName = "1.pdf";
            if (StringUtils.isNotNull(title)) {
                fileName = title + ".pdf";
            }
            try {
                download(fileName, targetPath, request, response);
                FileUtil.deleteChildrenFile(new File(basePath));
            } catch (Exception e) {
                e.printStackTrace();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    /**
     * 生成PDF模板
     *
     * @param id
     * @param model
     * @return
     */
    @RequestMapping("/export2PDF")
    public String export2PDF(String id, Model model) {
        Article article = articleService.get(id);
        model.addAttribute("content", article.getContent());
        return "jsp/doc/export/wkhtmlToPdf";
    }

    /**
     * 生成PDF
     *
     * @param id
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("/export2PDF2")
    public Object export2PDF2(String id, HttpServletRequest request,
                              HttpServletResponse response) throws Exception {
        Article article = articleService.get(id);
        String url = Const.DOMAIN + "/article/export2PDF?id=" + id;
        String path = Const.BASE_UPLOAD_PATH + File.separator + article.getTitle() + ".pdf";
        System.out.println(path);
        boolean b = WkhtmlToPDF.convert(url, path);
        if (b) {
            List<String> list = new ArrayList<String>();
            list.add(article.getTitle() + ".pdf");
            list.add(path);
            return renderSuccess(list);
        }
        return renderError("导出文件发生异常");
    }

    /**
     * 下载
     *
     * @param name
     * @param path
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping("/download")
    public void downloadPDF(String name, String path, HttpServletRequest request,
                            HttpServletResponse response) throws Exception {
        System.out.println("name=" + name);
        System.out.println("path=" + path);
        if (StringUtils.isNotNull(name) && StringUtils.isNotNull(path)) {
            download(name, path, request, response);
            File f = new File(path);
            f.delete();
            System.out.println("删除文件：" + name);
        }
    }


    /**
     * 导出为word
     *
     * @param id
     * @param request
     * @param response
     */
    @RequestMapping("/export2Word")
    public void exportWord(String id, HttpServletRequest request, HttpServletResponse response) {
        Article article = articleService.get(id);
        String content = article.getContent();
        String title = article.getTitle();
        String basePath = request.getServletContext().getRealPath("/static/temp");
        File baseFile = new File(basePath);
        if (!baseFile.exists()) {
            baseFile.mkdirs();
        }
        String path = basePath + File.separator + "temp.md";
        FileUtil.writeFile(path, content);
        String targetPath = basePath + File.separator + title + ".docx";
        if (StringUtils.isNull(title)) {
            targetPath = basePath + File.separator + "1.docx";
        }
        try {
            FileFactory.produce(new File(path), targetPath);
            String fileName = "1.docx";
            if (StringUtils.isNotNull(title)) {
                fileName = title + ".docx";
            }
            try {
                download2(fileName, targetPath, request, response);
                FileUtil.deleteChildrenFile(new File(basePath));
            } catch (Exception e) {
                e.printStackTrace();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    /**
     * 导出为markdown
     *
     * @param id
     * @param request
     * @param response
     */
    @RequestMapping("/exportMd")
    public void exportMd(String id, HttpServletRequest request, HttpServletResponse response) {
        Article article = articleService.get(id);
        String content = article.getContent();
        String title = article.getTitle();
        String basePath = request.getServletContext().getRealPath("/static/temp");
        File baseFile = new File(basePath);
        if (!baseFile.exists()) {
            baseFile.mkdirs();
        }
        String path = basePath + File.separator + title + ".md";
        FileUtil.writeFile(path, content);
        String targetPath = basePath + File.separator + title + ".md";
        if (StringUtils.isNull(title)) {
            targetPath = basePath + File.separator + "1.md";
        }
        try {
            String fileName = title + ".md";
            download2(fileName, targetPath, request, response);
            FileUtil.deleteChildrenFile(new File(basePath));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
